import { useEffect, useState, SyntheticEvent } from 'react';
import { SearchWord } from '@indexea/sdk';
import { SearchContext } from '@indexea/sdk/context';
import config from '../../config.json';
import { useIndexeaSearch } from '../hooks';
import { Indexea } from '../openapi';

const indexea = new Indexea(config.api, '', config.widget);

// export type HotwordsProps = {
//   context: SearchContext
//   attrs: any
//   search: (q: string) => void
// }

/**
 * 显示搜索热词
 * @param context
 * @param attrs
 * @param search
 * @returns
 */
export default function () {
  const { context, layout, search } = useIndexeaSearch();

  const [words, setWords] = useState<SearchWord[]>([]);

  useEffect(() => {
    // @ts-ignore show_count maybe string or number, should convert to number as safe
    indexea.hotwords(context.query, 'year', layout.hotWords.show_count || 5).then(setWords);
  }, [context.query]);

  return (
    <ul className="nav">
      {words.map(word => (
        <li className="nav-item" key={word.q}>
          <a
            className="nav-link m-0 px-2"
            href={'?q=' + word.q}
            onClick={e => doSearch(e, word.q || '')}
          >
            {word.q}
          </a>
        </li>
      ))}
    </ul>
  );

  function doSearch(e: SyntheticEvent, q: string) {
    e.preventDefault();
    search(q);
  }
}
